package cn.fl.ref.fribaseinfo.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import cmm.comm.facade.framework.api.ISysDictionaryApiService;
import cmm.mid.core.framework.page.DataResultVO;
import cmm.mid.core.framework.page.KeyValueVO;
import cmm.mid.core.framework.page.ListPageVO;
import cmm.mid.core.framework.page.Pager;
import cmm.web.core.framework.controller.BaseController;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.CollectionUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.framework.constant.DictionaryConstant;
import cn.fl.ref.fribaseinfo.service.IFriBaseInfoService;
import cn.fl.ref.fribaseinfo.service.IFundRasInsLimService;
import cn.fl.ref.fribaseinfo.vo.FundRasInsLimVO;
import cn.fl.system.constant.SysLogConstant;
import cn.fl.system.service.ISysUlFilesRecService;
import fl.ref.fribaseinfo.condition.FundRasInsLimQueryCondition;
import fl.ref.fribaseinfo.constant.FriBaseInfoConstant;

/**
 * @Description: 资管机构限额
 */
@Controller
@RequestMapping("/rfbase/fundRasInsLim")
public class FundRasInsLimController extends BaseController {

	private static final Logger logger = LoggerFactory.getLogger(FundRasInsLimController.class);

	@Autowired
	private IFundRasInsLimService fundRasInsLimService;

	/**
	 * 数据字典服务
	 */
	@Autowired
	private ISysDictionaryApiService sysDictionaryApiService;

	/**
	 * 附件服务
	 */
	@Autowired
	private ISysUlFilesRecService sysUlFilesRecService;
	@Autowired
	private IFriBaseInfoService friBaseInfoService;
	
	/**
	 * 初始化列表
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/initList.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object initList(HttpServletRequest request, HttpServletResponse response) {
		String currentPage = request.getParameter("page");
		String pageSize = request.getParameter("pagesize");
		String insId = request.getParameter("insId");
		Pager page = new Pager();
		if (StringUtils.isNotEmpty(currentPage)) {
			page.setCurrentPage(Integer.parseInt(currentPage));
		}

		if (StringUtils.isNotEmpty(pageSize)) {
			page.setEveryPage(Integer.parseInt(pageSize));
		}

		FundRasInsLimQueryCondition qc = new FundRasInsLimQueryCondition();
		if (StringUtils.isNotEmpty(insId)) {
			//TODO SOMTHING
			qc.setInsId(insId);
		}
		page.setCondition(qc);

		//TODO SOMETHING
		Pager pager = this.fundRasInsLimService.searchListPage(page);
		List<FundRasInsLimVO> list = (List<FundRasInsLimVO>) pager.getResultList();
		ListPageVO<FundRasInsLimVO> listPage = new ListPageVO<FundRasInsLimVO>(list, pager.getTotalCount());
		BaseLogUtils.info(logger, "initList", "查询数据完成. DATA:" + JSONObject.toJSONString(page), CurrentThreadContext.getCurrentUserName());
		return listPage;
	}

	/**
	 * 删除数据
	 */
	@RequestMapping(value = "/removeById.do", method = {RequestMethod.GET })
	@ResponseBody
	public DataResultVO removeById(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String id = request.getParameter("id");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_DELETE_SUCC);
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			return result;
		}
		try {
			this.fundRasInsLimService.removeById(Long.valueOf(id));
			BaseLogUtils.info(logger, "removeById", "删除数据.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "removeById", "删除数据失败.[id="+id+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "removeById", "删除数据失败.[id="+id+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}

		return result;
	}

	/**
	 * 得到一条记录
	 * 
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/getById.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object getById(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String id = request.getParameter("id");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_OPERATE_SUCC);
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			BaseLogUtils.error(logger, "getById", "获取数据,主键不存在.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
			return result;
		}
		
		try {
			FundRasInsLimVO vo = this.fundRasInsLimService.selectById(Long.valueOf(id));
			if(null == vo){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_QUERY_DATA_IS_EMPTY);
				BaseLogUtils.info(logger, "getById", "获取数据,数据不存在.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
			}
			result.setData(vo);
			BaseLogUtils.info(logger, "getById", "获取数据.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
		}catch(BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "getById", "获取失败.[id="+id+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch(Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "getById", "获取失败.[id="+id+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}

	/**
	 * 新增
	 */
	@RequestMapping(value = "/add.do", method = { RequestMethod.POST })
	@ResponseBody
	public Object add(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String name = request.getParameter("name");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_ADD_SUCC);
		FundRasInsLimVO entity = null;
		try {
			entity = new FundRasInsLimVO();
			//TODO ADD PARAM
			Long id = this.fundRasInsLimService.add(entity);
			result.setData(id);
			BaseLogUtils.info(logger, "add", "新增数据.[id="+id+"] DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "add", "新增数据失败.DATA:" + JSONObject.toJSONString(entity) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "add", "新增数据失败.DATA:" + JSONObject.toJSONString(entity) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}

		return result;
	}

	/**
	 * 修改
	 */
	@RequestMapping(value = "/modify.do", method = { RequestMethod.POST,RequestMethod.GET })
	@ResponseBody
	public Object modify(FundRasInsLimVO entity,HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String id = request.getParameter("id");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_UPDATE_SUCC);
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			BaseLogUtils.info(logger, "modify", "修改数据,主键不存在.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
			return result;
		}
		try {
				
			//entity.setName(name);
			//TODO ADD PARAM
			boolean success = this.fundRasInsLimService.modify(entity);
			if(!success){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
				BaseLogUtils.info(logger, "modify", "修改失败.[id="+id+"] DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
			}
			BaseLogUtils.info(logger, "modify", "修改成功.[id="+id+"] DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "modify", "修改失败.[id="+id+"] DATA:" + JSONObject.toJSONString(entity) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "modify", "修改失败.[id="+id+"] DATA:" + JSONObject.toJSONString(entity) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}
	/**
	 *  查询列表
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/searchList.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object searchList(HttpServletRequest request, HttpServletResponse response) {
		String insId = request.getParameter("insId");
		Map result=new HashMap<String, Object>();
		FundRasInsLimQueryCondition qc = new FundRasInsLimQueryCondition();
		if (StringUtils.isNotEmpty(insId)) {
			//TODO SOMTHING
			qc.setInsId(insId);
		}
		
		//TODO SOMETHING
		
		List<FundRasInsLimVO> list = (List<FundRasInsLimVO>) this.fundRasInsLimService.searchList(qc);
		BaseLogUtils.info(logger, "initList", "查询数据完成. DATA:" + JSONObject.toJSONString(qc), CurrentThreadContext.getCurrentUserName());
		result.put("data", list);
		List<KeyValueVO> list2 = friBaseInfoService.getKvList( DictionaryConstant.CODE_PRJ_TYPE_CD);
		result.put("types", list2);
		return result;
	}
	/**
	 * 修改 批量修改 设备限额信息
	 */
	@RequestMapping(value = "/batchUpdateLim.do", method = { RequestMethod.POST,RequestMethod.GET })
	@ResponseBody
	public Object batchUpdateLim(FundRasInsLimVO entity,HttpServletRequest request, HttpServletResponse response) throws BaseException {
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_UPDATE_SUCC);
		String insId = request.getParameter("dataId");//金融机构insId
		String limArrayStr = request.getParameter("typeArray");
		BaseLogUtils.newServiceLogger("typeJsonArray："+JSON.toJSONString(request.getParameter("typeArray"))).info();
		try {
			//添加资管机构限额
			List<FundRasInsLimVO> limVOList = new ArrayList<>();//前台传递结果集
			if(StringUtils.isNotBlank(limArrayStr)) {
				JSONArray limJson = JSONArray.parseArray(limArrayStr);
				if (!limJson.isEmpty() && limJson!=null && limJson.size() > 0) {
					for (int i = 0; i < limJson.size(); i++) {
						FundRasInsLimVO limVO = JSONObject.toJavaObject(limJson.getJSONObject(i), FundRasInsLimVO.class);
						limVOList.add(limVO);
					}
				}
			}
			//已存在数据库设备限额管理
			FundRasInsLimQueryCondition qc = new FundRasInsLimQueryCondition();
			if (StringUtils.isNotEmpty(insId)) {
				qc.setInsId(insId);
			}
			List<FundRasInsLimVO> oldLimlist = (List<FundRasInsLimVO>) this.fundRasInsLimService.searchList(qc);
			//新增 or 更新 or 作废
			if (CollectionUtils.isNotEmpty(limVOList)) {
				for (FundRasInsLimVO limVO : limVOList) {
					// 如果没有该记录就新增
					if (null == limVO.getId()) {
						limVO.setInsId(insId); 
						limVO.setCrtUsrId(CurrentThreadContext.getCurrentUserId());
						fundRasInsLimService.add(limVO);
					}
					// 如果有该记录就修改 比对之前已有的记录 如果存在就不移除
					else {
						limVO.setMdfUsrId(CurrentThreadContext.getCurrentUserId());
						fundRasInsLimService.modify(limVO);
						for (int i = 0; i < oldLimlist.size(); i++) {
							FundRasInsLimVO oldLimVO = oldLimlist.get(i);
							if (oldLimVO.getId().longValue() == limVO.getId().longValue()) {
								oldLimlist.remove(oldLimVO);
							}
						}
					}
				}
				if (CollectionUtils.isNotEmpty(oldLimlist)) {
					for (FundRasInsLimVO oldVO : oldLimlist) {
						fundRasInsLimService.removeById(oldVO.getId());
					}
				}
			}
			BaseLogUtils.info(logger, "modify", "修改成功.[insId="+insId+"] DATA:" + JSONObject.toJSONString(limArrayStr), CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "modify", "修改失败.[insId="+insId+"] DATA:" + JSONObject.toJSONString(limArrayStr) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "modify", "修改失败.[insId="+insId+"] DATA:" + JSONObject.toJSONString(limArrayStr) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}
}
